package com.view;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.risen.androidwcc.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.maincode.WCCBaseActivity;
import com.maincode.model.ImgBean;
import com.util.CrameUtils;
import com.util.Tools;

public class GrideViewImgListView extends FrameLayout {
    private Context context;
    @ViewInject(R.id.gridView)
    private GridView gridView;
    private AdapterManager<ImgBean> myAdapter;
    // private List<ImgBean> list = new ArrayList<ImgBean>();
    private CrameUtils crameUtils;
    private int maxSum = 0;
    private int position = -1;
    private String value;
    private boolean isUpdate = false;
    // 是否是编辑（编辑的时候有删除，修改，添加等功能）不是编辑就是查看（不是编辑的功能就自己重写listView的点击事件）
    private boolean isRead = false;

    /**
     * //是否是编辑（编辑的时候有删除，修改，添加等功能）不是编辑就是查看（不是编辑的功能就自己重写listView的点击事件）
     *
     * @param isRead
     */
    public void setRead(boolean isRead) {
        this.isRead = isRead;
    }

    /**
     * 获得横向ListView控件
     *
     * @return
     */
    public GridView getGridView() {
        return gridView;
    }

    public GrideViewImgListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);

    }

    private void init(final Context context) {
        this.context = context;
        View currentLayout = LayoutInflater.from(context).inflate(R.layout.grideview_img_list_view, null);
        ViewUtils.inject(this, currentLayout);
        this.addView(currentLayout);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        this.setLayoutParams(layoutParams);
        crameUtils = new CrameUtils();
    }

    private void showDialog(Context context) {
        final WCCBaseActivity activity = (WCCBaseActivity) context;
        MyPhotoDialog dialog = new MyPhotoDialog.Builder(context).setListener(new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: // 拍照
                        crameUtils.camera(activity);
                        dialog.dismiss();
                        break;
                    case 1: // 从相册选择
                        crameUtils.album(activity);
                        dialog.dismiss();
                        break;

                }
            }
        }).create();
        dialog.show();
        LinearLayout contorl_layouts = (LinearLayout) dialog.findViewById(R.id.contorl_layouts);
        contorl_layouts.setVisibility(View.GONE);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        WCCBaseActivity activity = (WCCBaseActivity) context;
        switch (requestCode) {
            case CrameUtils.CAMERA:
                if (crameUtils.saveFile != null) {
                    String path = crameUtils.saveFile.getAbsolutePath();
                    setImgData(path, value);
                }
                break;
            case CrameUtils.ALBUM:
                if (data == null) {
                    return;
                }
                Uri originalUri = data.getData();
                if (originalUri == null) {
                    return;
                }
                String path = crameUtils.getPath(context, originalUri);
                setImgData(path, value);
                break;

            default:
                break;
        }
    }

    private void setImgData(String path, String value) {
        if (!Tools.StringHasContent(path)) {
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            for (ImgBean bean : myAdapter.getList()) {
                if (path != null && path.equals(bean.getPath())) {
                    Toast.makeText(context, "已上传此图片", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (this.isUpdate) {
                ImgBean bean = new ImgBean(path, value);
                myAdapter.setData(position, bean);
            } else {
                ImgBean bean = new ImgBean(path, value);
                myAdapter.addData(bean, position);
                if (isMax()) {
                    deleteDefaultImg();
                } else {
                    addDefauleImg();
                }
            }
        }
    }

    /**
     * 设置最大的图片个数
     *
     * @param maxSum
     */
    public void setMaxSum(int maxSum) {
        this.maxSum = maxSum;
    }

    /**
     * 检查是否达到上线
     */
    private boolean isMax() {
        int count = 0;
        for (ImgBean bean : myAdapter.getList()) {
            if (Tools.StringHasContent(bean.getPath())) {
                count++;
            }
        }
        return count >= maxSum;
    }

    /**
     * 删除默认的类型显示图片
     *
     */
    private void deleteDefaultImg() {

        for (int i = 0; i < myAdapter.getList().size(); i++) {
            ImgBean imgBean = myAdapter.getList().get(i);
            if (!Tools.StringHasContent(imgBean.getPath())) {
                myAdapter.deleteFromIndex(i);
            }
        }
    }

    public boolean hasDefaultImg() {
        for (ImgBean bean : myAdapter.getList()) {
            if (!Tools.StringHasContent(bean.getPath())) {
                return true;
            }
        }
        return false;
    }

    public void init() {
        int count = 0;
        for (ImgBean bean : myAdapter.getList()) {
            if (Tools.StringHasContent(bean.getPath())) {
                count++;
            }
        }
        if (count >= this.maxSum) {
            this.deleteDefaultImg();
        }
    }

    /**
     * 添加默认的类型显示图片
     *
     */

    public void addDefauleImg() {
        if (!hasDefaultImg()) {
            int index = -1;
            for (ImgBean imgBean : myAdapter.getList()) {
                if (Tools.StringHasContent(imgBean.getPath())) {
                    index++;
                }
            }
            ImgBean imgBean = new ImgBean("", "");
            if (index >= 0) {
                myAdapter.addData(imgBean, index);
            }
        }
    }

    /**
     * 设置适配器和item点击事件
     *
     */
    public void setAdapter(AdapterManager<ImgBean> myAdapter) {
        if (this.myAdapter != null || myAdapter == null) {
            return;
        }
        this.myAdapter = myAdapter;
        gridView.setAdapter(this.myAdapter);
        if (!isRead) {
            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    GrideViewImgListView.this.position = arg2;
                    ImgBean bean = GrideViewImgListView.this.myAdapter.getItem(arg2);
                    GrideViewImgListView.this.value = bean.getValue();
                    GrideViewImgListView.this.isUpdate = !(bean.getPath() == null || bean.getPath().equals(""));
                    showDialog(context);
                }
            });
        } else {
            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                    ArrayList<String> pathArr = new ArrayList<String>();
                    for (int i = 0; i < GrideViewImgListView.this.myAdapter.getCount(); i++) {
                        pathArr.add(GrideViewImgListView.this.myAdapter.getItem(i).getPath());
                    }

                    Intent intent = new Intent(context, ImagesListView.class);
                    Bundle bl = new Bundle();
                    bl.putStringArrayList("img_list", pathArr);
                    intent.putExtra("index", arg2);
                    intent.putExtra("bl", bl);
                    context.startActivity(intent);
                }
            });
        }
    }
}
